import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 把并发调用变成交替调用
 */
public class B交替打印FooBar {
    private static class 方案一Semaphore{
         static class FooBar{
            private int n;
            public FooBar(int n){
                this.n=n;
            }
            Semaphore foo=new Semaphore(1);
            Semaphore bar=new Semaphore(0);
            public void foo(Runnable printFoo){
                for (int i = 0; i < n; i++) {
                    try {
                        foo.acquire();
                        printFoo.run();
                        bar.release();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

            public void bar(Runnable printBar){
                for (int i = 0; i < n; i++) {
                    try {
                        bar.acquire();
                        printBar.run();
                        foo.release();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

            public static void main(String[] args) {
                B交替打印FooBar.方案一Semaphore.FooBar a=new B交替打印FooBar.方案一Semaphore.FooBar(10);
                new Thread(()->a.foo(()-> System.out.println("foo"))).start();
                new Thread(()->a.bar(()-> System.out.println("bar"))).start();
            }
        }
    }
    private static class 方案二Lock公平锁{
        static class FooBar{
            private int n;
            public FooBar(int n){
                this.n=n;
            }
            Lock lock=new ReentrantLock(true);
            volatile boolean permitFoo=true;
            public void foo(Runnable printFoo){
                for (int i = 0; i < n; i++) {
                    lock.lock();
                    try {

                    }finally {

                    }
                    if (permitFoo) {
                        printFoo.run();
                        i++;
                        permitFoo=false;
                    }
                }
            }
        }

    }
    private static class 方案三无锁{}
    private static class 方案四CyclicBarrier{}
}
